from threading import Timer

import matplotlib.pyplot as plt
import pandas as pd
from DirMonitor import DirMonitor
from TopFrameParser import TopFrameParser
import matplotlib.dates as mdates

'''
adb -s 61A4B000188 root;i=0;while true;do ((i++)) ;echo "Saving :"$i".txt"; adb -s 61A4B000188 shell "echo \" TIME: \"`date "+%y%m%d%H%M%S"`" >>../.temp;  adb -s 61A4B000188 shell top -n 1 >> ../.temp; mv ../.temp ./$i.txt;sleep 1;done
'''


def handle_close(event):
    global df
    print('quit')


def update():
    global df
    added_files = dm.watch_changes()
    if len(added_files) == 0:
        return
    frames = TopFrameParser.parse_files(added_files)
    df = df.append(frames)
    df = df.sort_index()
    df_dvg = df.rolling(60, min_periods=1).mean()

    ax.clear()
    df_dvg.rename(columns={
        'dashcam': 'dashcam_avg',
        'cpu_usage': 'cpu_usage_avg',
        'camera_provider': 'camera_provider_avg',
        'codec': 'codec_avg',
        'cameraserver': 'cameraserver_avg',
        'top': 'top_avg',
    }, inplace=True)
    df_data = df.join(df_dvg)
    df_data.plot(ax=ax, style=['--', '--', '--', '--', '--', '--', '-', '-', '-', '-', '-', '-'])

    # ax.plot(df_data.index, df_data['dashcam'], lw=1, linestyle='--', color='#D3D3D3')
    # ax.plot(df_data.index, df_data['dashcam_avg'], lw=2, linestyle='-', color='#006400')
    # ax.plot(df_data.index, df_data['cpu_usage'], lw=1, linestyle='--', color='#D3D3D3')
    # ax.plot(df_data.index, df_data['cpu_usage_avg'], lw=2, linestyle='-', color='#8B0000')
    # df.plot(ax=ax, grid=True, style=['--', '-.'], subplots=True, layout=(2, 1))
    # df_dvg.plot(ax=ax, grid=True, style=['-', '-'], subplots=True, layout=(2, 1))
    # df.plot(ax=ax, grid=True, style=['--', '-.'])
    # plt.pause(1)
    plt.show()


if __name__ == '__main__':
    # plt.ion()
    fig = plt.figure()
    fig.canvas.mpl_connect('close_event', handle_close)
    ax = fig.add_subplot(111)  # Create an axes.
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
    plt.gcf().autofmt_xdate()

    df = pd.DataFrame()
    dm = DirMonitor('/home/ole/workspace/1_project/9010/JIRA/fps/top2/top')
    # while True:
    update()
    # plt.pause(10000)
